package com.we.tickets.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.we.tickets.contracts.event.EventManagement;
import com.we.tickets.contracts.ticketing.TicketingManagement;
import com.we.tickets.dao.EventDao;
import com.we.tickets.dao.TicketDao;
import com.we.tickets.dao.UserDao;
import com.we.tickets.service.EventService;
import com.we.tickets.util.CommonUtil;
import com.we.tickets.util.constants.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.StaticGasProvider;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.List;

@Service
public class EventServiceImpl implements EventService {
    @Autowired
    private Web3j web3j;

    @Autowired
    private EventDao eventDao;

    @Autowired
    private TicketDao ticketDao;

    @Autowired
    private UserDao userDao;

    @Override
    public JSONObject createEvent(JSONObject jsonObject) {
        String privateKey = userDao.getUserPrivateKeyById(jsonObject.getInteger("organizer_id"));
        Credentials credentials = Credentials.create(privateKey);
        ContractGasProvider contractGasProvider = new StaticGasProvider(BigInteger.valueOf(20000000000L), BigInteger.valueOf(6721975L));
        EventManagement eventManagement = EventManagement.load(Contracts.EventManagement ,web3j, credentials, contractGasProvider);
        TicketingManagement ticketingManagement = TicketingManagement.load(Contracts.TicketingManagement, web3j, credentials, contractGasProvider);

        eventDao.createEvent(jsonObject);
        int event_id = jsonObject.getInteger("id");
        try {
            eventManagement.createEvent(BigInteger.valueOf(event_id)).sendAsync().get();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonUtil.errorJson("操作失败");
        }

        JSONArray tickets = jsonObject.getJSONArray("tickets");
        for (int i = 0; i < tickets.size(); i++) {
            JSONObject ticket = tickets.getJSONObject(i);
            ticket.put("event_id", event_id);
            ticketDao.createTicket(ticket);
            BigInteger returnEndTimestamp = (ticket.getString("returnEndTime").equals("")) ? BigInteger.valueOf(0) : BigInteger.valueOf(Timestamp.valueOf(ticket.getString("returnEndTime")).getTime());
            BigInteger transferEndTimestamp = (ticket.getString("transferEndTime").equals("")) ? BigInteger.valueOf(0) : BigInteger.valueOf(Timestamp.valueOf(ticket.getString("transferEndTime")).getTime());
            try {
                ticketingManagement.createTicket(
                        BigInteger.valueOf(ticket.getInteger("id")),
                        BigInteger.valueOf(event_id),
                        ticket.getBoolean("returnable"),
                        ticket.getBoolean("transferable"),
                        BigInteger.valueOf(Timestamp.valueOf(ticket.getString("validBefore")).getTime()),
                        returnEndTimestamp,
                        transferEndTimestamp,
                        BigInteger.valueOf(Timestamp.valueOf(ticket.getString("saleEndTime")).getTime()),
                        BigInteger.valueOf(ticket.getInteger("price") * 100),
                        BigInteger.valueOf(ticket.getInteger("sum")),
                        BigInteger.valueOf(ticket.getInteger("maxNum"))
                ).sendAsync().get();
            } catch (Exception e) {
                e.printStackTrace();
                return CommonUtil.errorJson("操作失败");
            }
        }

        return CommonUtil.successJson();
    }

    @Override
    public JSONObject getAllEvents() {
        List<JSONObject> eventList = eventDao.getAllEvents();
        return CommonUtil.successJson(eventList);
    }

    @Override
    public JSONObject getEventBasicInfo(JSONObject jsonObject) {
        JSONObject res = eventDao.getEventBasicInfo(jsonObject);
        return CommonUtil.successJson(res);
    }

    @Override
    public JSONObject getEventDetails(JSONObject jsonObject) {
        String details = eventDao.getEventDetails(jsonObject);
        return CommonUtil.successJson(details);
    }

    @Override
    public JSONObject getEventsOfOrganizer(JSONObject jsonObject) {
        List<JSONObject> eventList = eventDao.getEventsOfOrganizer(jsonObject);
        return CommonUtil.successJson(eventList);
    }

    @Override
    public JSONObject getTicketsByEventId(JSONObject jsonObject) {
        List<JSONObject> ticketList = ticketDao.getTicketsByEventId(jsonObject);
        return CommonUtil.successJson(ticketList);
    }

    @Override
    public JSONObject getTicketById(JSONObject jsonObject) {
        JSONObject ticketInfo = ticketDao.getTicketById(jsonObject);
        return CommonUtil.successJson(ticketInfo);
    }
}
